#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include<unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#define NUM 10 
typedef void(*func_t)();//函数指针！

func_t handlerTask[NUM];//函数指针数组！
void task1()
{
    printf("handler task1\n");
}
void task2()
{
    printf("handler task2\n");
}
void task3()
{
    printf("handler task3\n");
}
void loadTask()
{
    memset(handlerTask,0,sizeof(handlerTask));
    handlerTask[0] = task1;
    handlerTask[1] = task2;
    handlerTask[2] = task3;

}
int main()
{
    pid_t id = fork();
    if(id == 0)
    {
        //子进程
        int cnt = 5;
        while(cnt)
        {
            printf("i am child pid = %d ,ppid = %d\n",getpid(),getppid());
            --cnt;
            sleep(1);
        }
        exit(10);
        
    }
    //parent
    loadTask();
    int status = 0;
    while(1)
    {
          pid_t ret = waitpid(id,&status,WNOHANG);//非阻塞状态！
          if(ret == 0)
          {
              //子进程没有退出，waitpid没有等待失败！仅仅是检测到子进程没有退出！
              printf("wait done but the child is runing .....\n");
              sleep(1);
              for(int i = 0;handlerTask[i] != NULL;i++)
              {
                  handlerTask[i]();//采用回调的方式，执行我们想让父进程在空闲的时候做的事情！

              }
          }
          else if(ret > 0) 
          {
              //waitpid调用成功！且子进程退出！
              printf("wait succeeful :%d,sign number : %d,child exit code  :%d\n",ret,(status & 0x7F),((status >> 8)& 0xFF) );
              break;
          }
          else 
          {
              //waitpid调用失败！
              printf("waitpid call failed\n");
              break;
          }
    }
  //  int status = 0;
  //  pid_t ret  =waitpid(id,&status,0);
  //  if(ret > 0)
  //  {
  //      if(WIFEXITED(status))
  //      {
  //          printf("exit code :%d \n",WEXITSTATUS(status));
  //      }
  //      else 
  //      {
  //          printf("child exit no normal!\n");
  //      }
  //      //printf("wait succeeful :%d,sign number : %d,child exit code  :%d\n",ret,(status & 0x7F),((status >> 8)& 0xFF) );
  //  }
  //  sleep(5);

     return 0;
}

